'use strict'

const http = require('http');

let html = `
    <!DOCTYPE html>
    <html>
    <head>
        <title>First Sever</title>
    </head>
    <body>
        <div>Node.js in service</div>
    </body>
    </html>
`
let routerTable = {
    '/' : async (request, response) => {
        response.setHeader('content-type', 'text/html; charset = utf-8');
        response.end(html);
    },

    '/x/y' : async (request,response) => {
        response.end('--ok--');
    },

    '/x/y/z': async (request, response) => {
        let bufferList = [];
        let totalLength = 0;

        //console.log(request);
        request.on('data', chunk => {
            totalLength += chunk.length;
            bufferList.push(chunk);
            //console.log(chunk.toString());
        })

        let bodyData = null;

        request.on('end', () => {
            if(bufferList.length > 0){
                bodyData = Buffer.concat(bufferList, totalLength);
            }
            bufferList = [];

            if(bodyData){
                response.setHeader('content-type', 'text/plain; charset = utf-8');
                response.end(bodyData);
            }
            else{
                response.end();
            }
        })

    }
}

let serv = http.createServer((request, response) => {

    //console.log(request.url,request.headers,request.method);

    // if(request.url !== '/x/y/z'){
    //     response.statusCode = 404;
    //     response.end('page not found');
    //     return
    // }

    if(routerTable[request.url] === undefined){
        response.statusCode = 404;
        response.end('page not found');
        return
    }

    routerTable[request.url](request, response);

    // let bufferList = [];
    // let totalLength = 0;

    // //console.log(request);
    // request.on('data', chunk => {
    //     totalLength += chunk.length;
    //     bufferList.push(chunk);
    //     //console.log(chunk.toString());
    // })

    // let bodyData = null;

    // request.on('end', () => {
    //     if(bufferList.length > 0){
    //         bodyData = Buffer.concat(bufferList, totalLength);
    //     }
    //     bufferList = [];

    //     if(bodyData){
    //         response.setHeader('content-type', 'text/plain; charset = utf-8');
    //         response.end(bodyData);
    //     }
    //     else{
    //         response.setHeader('content-type', 'text/html; charset = utf-8');
    //         response.end(html);
    //     }
    // })

});

serv.listen(3456);